package com.bluetooth;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.os.Handler;
import android.util.Log;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.util.UUID;

/**
 * Created by Administrator on 2017/9/28.
 * 和一个服务器的全部通话
 */

public class Dispatcher{
    private BluetoothSocket socket;
    private final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
    private InputStream in;
    private OutputStream out;

    public AcceptThread getAcceptThread() {
        return acceptThread;
    }

    private AcceptThread acceptThread;
    public Dispatcher(BluetoothAdapter bluetoothAdapter, String address)
    {
        BluetoothDevice  device = bluetoothAdapter.getRemoteDevice(address);//远程服务器

            try {
                socket = device.createRfcommSocketToServiceRecord(MY_UUID);
                //开始连接蓝牙，如果没有配对则弹出对话框提示我们进行配对
                try {
                    socket.connect();
                    Log.e("","Connected");
                } catch (IOException e) {
                    Log.e("",e.getMessage());
                    try {
                        Log.e("","trying fallback...");

                        socket =(BluetoothSocket) device.getClass().getMethod("createRfcommSocket", new Class[] {int.class}).invoke(device,1);
                        socket.connect();

                        Log.e("","Connected");
                    }
                    catch (Exception e2) {
                        Log.e("", "Couldn't establish Bluetooth connection!");
                    }
                }
                in=socket.getInputStream();
                out=socket.getOutputStream();
            } catch (IOException e) {
                e.printStackTrace();
                this.destory();
            }


    }
    public void acceptMessage(Context context,Handler handler,double value)
    {
            if(acceptThread!=null){
                acceptThread.exit();
            }
            acceptThread=new AcceptThread(in,context,handler,value);
            acceptThread.start();
    }
    public void acceptMessage(Context context,Handler handler)
    {

       new AcceptThread(in,context,handler).start();
    }

    public void sendMessage(String message)
    {
        new SendThread(out,message).start();
    }
    public void destory()
    {
        try {
            if(in!=null){
                in.close();
            }
            if(out!=null)
            {
                out.close();
            }
            if(socket!=null){
                socket.close();
            }


        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
